const Router = require('koa-router');
const router = new Router({
  prefix: '/v1/'
});
const {
  Auth
} = require('../../middlewares/auth.js');

const {
  Flow
} = require('../../models/flow.js');

const {
  Art
} = require('../../models/art.js');

const { ClassicValidator } = require('../../validators/validators.js');
const { Favor } = require('../../models/favor.js');
router.post('class', new Auth().m, async (ctx, next) => {
  ctx.body = ctx.auth;
})

router.post('latest', new Auth().m, async (ctx, next) => {
  const flow = await Flow.findOne({
    order: [
      ['index', 'DESC']
    ]
  });

  const art = await Art.getData(flow.art_id, flow.type);
  // art.dataValues.index = flow.index;
  art.setDataValue('index', flow.index);
  ctx.body = art;
});

router.post('/:type/:id/favor', new Auth().m, async (ctx, next) => {
  const v = await new ClassicValidator().validate(ctx);
  const id = v.get('path.id');
  const type = v.get('path.type');
  const art = await Art.getData(id, type);
  if (!art) {
    throw new Error('搞鸡毛!')
  }
  const like = await Favor.userLikeIt(id, type, ctx.auth.uid);
  ctx.body = {
    fav_nums: art.fav_nums,
    like_status: like
  };
});

// 获取所有喜欢的期刊的列表
router.get('/favor', new Auth().m, async ctx => {
  const uid = ctx.auth.uid;
  ctx.body = await Favor.getMyClassicFavors(uid);
});
// 获取某一个期刊
router.get('/:type/:id', new Auth().m, async ctx => {
  const v = await new ClassicValidator().validate(ctx);
  const id = v.get('path.id');
  const type = v.get('path.type');
  const artDetail = await new Art(id, type).getDetail(ctx.auth.uid);
  ctx.body = {
    art: artDetail.art,
    like_status: artDetail.like_status
  };
});



module.exports = router;